package com.eralink.unionuhfreader.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.brightek.thermallibrary.PrinterManager.WHPrinterManager;
import com.brightek.thermallibrary.sdk.BrState;
import com.brightek.whotherlib.Comm.SharedPreManager;
import com.eralink.unionuhfreader.MyApplication;
import com.eralink.unionuhfreader.R;
import com.eralink.unionuhfreader.base.BaseActivity;
import com.eralink.unionuhfreader.bean.AppConfirmOrderReqVO;
import com.eralink.unionuhfreader.bean.AppMemberUserInfoRespVO;
import com.eralink.unionuhfreader.bean.ProductOrderDo;
import com.eralink.unionuhfreader.bean.ProductVo;
import com.eralink.unionuhfreader.dialog.CommonDialog;
import com.eralink.unionuhfreader.http.Api;
import com.eralink.unionuhfreader.http.JsonCallBack;
import com.eralink.unionuhfreader.http.Result;
import com.eralink.unionuhfreader.netty.OneCardListen;
import com.eralink.unionuhfreader.util.ByteUtil;
import com.eralink.unionuhfreader.util.SharedPreferencesUtil;
import com.eralink.unionuhfreader.util.ToastUtil;
import com.lzy.okgo.model.Response;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class ScanPayActivity extends BaseActivity {
    Button btn_close;
    private String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_FINE_LOCATION,
            "android.permission.BLUETOOTH",
            "BLUETOOTH_CONNECT"
    };
    List<String> mPermissionList = new ArrayList<>();
    List<ProductVo> productVos;
    ProductOrderDo productOrderDo;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        //先取消上次订单
       // MyApplication.getInstance().cancelPaydata();
        btn_close=findViewById(R.id.btn_close);
        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
              //  showrefundDialog();
            }
        });
        String p=getIntent().getBundleExtra("p").getString("products");
        productVos= JSON.parseArray(p,ProductVo.class);
        productOrderDo = (ProductOrderDo) getIntent().getBundleExtra("p").getSerializable("productorder");
        //初始化handler
        WHPrinterManager.getInstance().initManager(this);
        WHPrinterManager.getInstance().addHandler(handler);
        initPermission();//申请权限
        //初始化
        SharedPreManager.getInstance().InitSharePre(this);
        MyApplication.getInstance().setOneCardListen(oneCardListen);
        sendData(productOrderDo.getRealTotalAmount());
    }
    OneCardListen oneCardListen = new OneCardListen() {
        @Override
        public void payCallBack(String cardNo, long payAmount, String sn) {
            while (cardNo.startsWith("0")) {
                cardNo = cardNo.substring(1, cardNo.length());
            }
            excCode(cardNo,"onecard");
        }
    };
    private void sendData(BigDecimal actmoney) {
        if (!MyApplication.connect_oncard) {
            return;
        }
        int sn = (int) SharedPreferencesUtil.getData(this, "sn", -1);
        if (sn == 65535) {
            sn = 0;
        } else {
            sn = sn + 1;
        }
        //5A 00 01 01 A2 00 04 00 00 00 04 A2
        byte[] data = new byte[10];
        //包序号
        String hexString = Integer.toHexString(sn);
        int datalen = 4 - hexString.length();
        for (int i = 0; i < datalen; i++) {
            hexString = "0" + hexString;
        }
        //byte[] data={0x00, 0x01,0x01, (byte) 0xA2, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04};
        byte[] byteArray = ByteUtil.hexStr2bytes(hexString);
        data[0] = byteArray[0];
        data[1] = byteArray[1];//包序号
        data[2] = (byte) 0x01;//命令类别
        data[3] = (byte) 0xA2;//命令码
        data[4] = (byte) 0x00;
        data[5] = (byte) 0x04;

        //金额数组
        String moneystr = Integer.toHexString(actmoney.multiply(new BigDecimal(100)).intValue());
        int moneylen = 8 - moneystr.length();
        for (int i = 0; i < moneylen; i++) {
            moneystr = "0" + moneystr;
        }
        byte[] moneyArray = ByteUtil.hexStr2bytes(moneystr);
        data[6] = moneyArray[0];
        data[7] = moneyArray[1];
        data[8] = moneyArray[2];
        data[9] = moneyArray[3];
        byte LRC = ByteUtil.calculateLRC(data);

        byte[] sendata = new byte[12];
        sendata[0] = (byte) 0x5A;
        for (int i = 1; i < 11; i++) {
            sendata[i] = data[i - 1];
        }
        sendata[11] = LRC;
        MyApplication.getInstance().sendData(sendata);
        Log.i("ykj520", "发送数据序列号:" + ByteUtil.bytes2HexStr(sendata));
        SharedPreferencesUtil.saveData(this, "sn", sn);
    }
    private ImageView imageViewToolbarUsb;
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case BrState.net_Connected:
                case BrState.bt_Connected:
                case BrState.usb_Connected:
                case BrState.ble_Connected:
                case BrState.com_Connected:{
                    //imageViewToolbarUsb.setImageResource(R.drawable.light_green);
                    break;
                }
                case BrState.ble_DisConnected:
                case BrState.net_DisConnected:
                case BrState.bt_DisConnected:
                case BrState.usb_DisConnected:
                case BrState.com_Disconnected:{

                    //imageViewToolbarUsb.setImageResource(R.drawable.light_grag);
                    break;
                }


                default:
                    break;

            }
        }
    };
    private void initPermission(){

        int mRequestCode = 1001;//权限请求码
        if (android.os.Build.VERSION.SDK_INT > 22) {
            mPermissionList.clear();//清空已经允许的没有通过的权限
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) !=
                        PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permission);
                }
            }
            //申请权限
            if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
                ActivityCompat.requestPermissions(this, permissions, mRequestCode);
            }

        }
    }



    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int action = event.getAction();
        switch (action) {
            case KeyEvent.ACTION_DOWN:
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
                    return super.dispatchKeyEvent(event);
                }
                int unicodeChar = event.getUnicodeChar();
                sb.append((char) unicodeChar);
                Log.e("MainActivity", "dispatchKeyEvent: " + unicodeChar + " " + event.getKeyCode() + " scancode=" + event.getScanCode());
                len++;
                startScan();
                return true;
            default:
                break;
        }
        return super.dispatchKeyEvent(event);
    }
    private Handler myHandler = new Handler();
    int oldLen = 0;
    int len = 0;
    boolean isScaning = false;
    private StringBuilder sb = new StringBuilder();
    private void startScan() {
        if (isScaning) {
            return;
        }
        isScaning = true;
        timerScanCal();
    }
    private void timerScanCal() {
        oldLen = len;
        myHandler.postDelayed(scan, 100);
    }
    Runnable scan = new Runnable() {
        @Override
        public void run() {
            if (oldLen != len) {
                timerScanCal();
                return;
            }
            isScaning = false;
            if (sb.length() > 0) {
                excCode(sb.toString(),"WxBToC");
                sb.setLength(0);
            }
        }
    };
    CommonDialog cashRefundDialog;
    private void showrefundDialog() {
        if (cashRefundDialog==null){
            cashRefundDialog = new CommonDialog(this, "请输入会员号或者扫描会员码").setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.tv_cancel:

                            break;
                        case R.id.tv_confirm:
                            if (v.getTag()==null){
                                showToast("请输入你的会员手机号");
                            }else{
                                excCode(v.getTag().toString(),"WxBToC");
                            }
                            break;
                    }

                    //SystemUIUtils.setStickFullScreen(MainActivity.this.getWindow().getDecorView());
                    cashRefundDialog.dismiss();
                }
            });
        }

        cashRefundDialog.show();
    }
    private void excCode(String code,String type) {
        code=code.replaceAll("[\r\n]+","");
        AppConfirmOrderReqVO appConfirmOrderReqVO=new AppConfirmOrderReqVO();
        appConfirmOrderReqVO.setOrderId(productOrderDo.getId());
        appConfirmOrderReqVO.setPayCode(code);
        appConfirmOrderReqVO.setPayType(type);//微信B扫C
        Api.confirmOrder(appConfirmOrderReqVO,new JsonCallBack<Result>(){
            @Override
            public void onSuccess(Response<Result> response) {
                Result result=response.body();
                if (result!=null&&result.isSucess()){
                    ToastUtil.showToast("支付成功");
                   // WHPrinterManager.getInstance().sendDataBySingle("博航收银系统");
                   /* for (ProductVo productVo : productVos) {
                        WHPrinterManager.getInstance().sendDataBySingle(productVo.getProductName()+"        "+productVo.getSalePrice());
                    }*/
                    finish();
                }else{
                    showToast(result.getMsg());
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        WHPrinterManager.getInstance().removeHandler(handler);//移除handler
        MyApplication.getInstance().cancelPaydata();
    }
}
